$NG.AllReady(function (page, { useAction, useClick, useImportExcelData, useUpdateRow, useUpdateRows, useAfterClick, useBeforeClick }) {
    const config = {
        bakRow: null
    }
    const dgrid1 = $NG.getCmpApi("p_form_htq_d1")
    const dgrid1_toobar = $NG.getCmpApi("toolbar_p_form_htq_d1")
    console.log('detail Ready');
    // 手动增行逻辑
    const addBtn = ['addrow', 'addchildren',]
    addBtn.forEach(item => {
        useAfterClick((args) => {
            const rows = dgrid1.getRows()
            rows[rows.length - 1].u_add = '1'
            dgrid1.refreshView()
        }, item)
    })
    dgrid1_toobar.insert({
        id: "dowloadFile",
        text: "下载导入模板",
        iconCls: "icon-New"
    });

    useClick(() => {
        $NG.open(location.origin + `/react/index.html?v=1754555236780#/customform/detail?id=6870000000000001&otype=view&busType=drmb&isSso=0&AppTitle=%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF-%E6%9F%A5%E7%9C%8B&menucode=ef350335-5167-3422-322a-04d09a0b5fdb`)
    }, 'dowloadFile')

    // 删除行(禁止删除导入)
    useBeforeClick((args) => {
        const checkrows = dgrid1.getSelectedData()
        if (args.containerId == 'p_form_htq_d1') {
            let delLock = true
            checkrows.forEach(item => {
                if (item.u_add != '1') {
                    delLock = false
                }
            })
            if (!delLock) {
                $NG.alert("删除行中包含导入的数据，不可删除！")
                return false
            }
        }
    }, "deleterow")
    useUpdateRows(({ args }) => {
        // console.log(`编辑`,);
        let rows = args[0]
        temps = rows.filter(item => {
            if (item.u_add == '1') {
                return item
            }
        })
        sumAmt(temps, null, true)
    }, "p_form_htq_d1")

    useUpdateRow(({ args, instance }) => {
        const row = args[0]
        if (row.u_add != '1') {
            $NG.alert("当前行是导入数据不可修改和删除!")
            console.log(`config.bakRow`, config.bakRow);
            let temp = config.bakRow.filter(item => {
                if (item.u_add == row.u_add) {
                    return item
                }
            })
            console.log(`temp`, temp);
            if (temp.length != 1) {
                $NG.alert("内部发生异常，异常会导致数据错误，请联系管理员！")
                return
            }
            temp = temp[0]
            for (let key in row) {
                row[key] = temp[key]
            }
        }
        instance.updateRow(row)
    }, "p_form_htq_d1")
    const keys = ['s_tree_no']
    useImportExcelData(function ({ args }) {
        // %对导入的excel数据进行加工处理，如果要阻止数据传递给业务，则直接返回false
        // %excelData 是一个引用类型，如果直接修改则不需要额外返回
        console.log(`导入的数据`, args);
        args[0].excelData.forEach(item => {
            item.u_add = generateUUID()
        })
        const bakRow = deepClone(args[0].excelData)
        config.bakRow = bakRow
        return args[0].excelData;
    }, 'p_form_htq_d1');

    // 计算
    function sumAmt(rows, instance, thread) {
        const run = (item, instance) => {
            return new Promise((resolve) => {
                queueMicrotask(() => {
                    item.u_hj = (Number(item.u_gcl) || 0) * (Number(item.u_dj) || 0)
                    if (instance) {
                        instance.updateRow(item)
                    } else {
                        dgrid1.refreshView()
                    }
                    resolve()
                })
            })
        }
        // 逻辑
        if (Array.isArray(rows)) {
            if (thread) {
                const threads = []
                rows.forEach(item => {
                    threads.push(run(item, instance))
                })
                // 并行
                if (window.u) {
                    clearTimeout(window.u)

                }
                console.log(`定时`,);
                window.u = setTimeout(() => {
                    console.log(`执行`,);
                    Promise.all(threads)
                }, 5000)
            } else {
                rows.forEach(item => {
                    run(item, instance)
                })
            }
        } else {
            console.log(`对象`,);
            run(rows, instance)
        }
    }


    // 深复制
    function deepClone(source, hash = new WeakMap()) {
        // 处理null和undefined
        if (source === null || typeof source !== 'object') {
            return source;
        }

        // 处理循环引用
        if (hash.has(source)) {
            return hash.get(source);
        }

        let clone;

        // 处理日期
        if (source instanceof Date) {
            clone = new Date();
            clone.setTime(source.getTime());
            hash.set(source, clone);
            return clone;
        }

        // 处理正则表达式
        if (source instanceof RegExp) {
            clone = new RegExp(source.source, source.flags);
            hash.set(source, clone);
            return clone;
        }

        // 处理数组和对象
        if (Array.isArray(source)) {
            clone = [];
        } else {
            clone = {};
        }

        // %存储到WeakMap，解决循环引用
        hash.set(source, clone);

        // 递归复制属性
        Reflect.ownKeys(source).forEach(key => {
            clone[key] = deepClone(source[key], hash);
        });

        return clone;
    }

    function generateUUID() {
        // UUID v4的格式为：xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
        // 其中y位为8、9、A或B

        // %生成随机16进制数的辅助函数
        function randomHex() {
            // 生成0-0xffff的随机数，转换为16进制并补全4位
            return Math.floor((1 + Math.random()) * 0x10000)
                .toString(16)
                .substring(1);
        }

        // 生成y位的值（8-11之间的随机数，16进制为8-b）
        const y = Math.floor(Math.random() * 4) + 8;

        return (
            randomHex() + '-' +
            randomHex() + '-' +
            '4' + randomHex().substring(1) + '-' +  // 第3段以4开头
            y.toString(16) + randomHex().substring(1) + '-' +  // 第4段以y开头
            randomHex() + randomHex()
        );
    }
}, function () {
    console.log('list Ready');
});